import axios from 'axios'
import config from '../config'

export function searchp (kw, page, orgIdAry, searchStr) {
  let query = ''

  if (orgIdAry && orgIdAry.length > 0) {
    query = 'organiza.id=in=' + orgIdAry.join(',')
  }

  if (kw) {
    if (query.length) {
      query += ';'
    }
    query += 'fullname=_like=' + kw
    query += ';telephone=_like=' + kw
    query += ';username=_like=' + kw
  }
  if (searchStr) {
    if (query.length) {
      query += ';'
    }
    query += searchStr
  }

  return axios.get(config.SERVER_URL + window.apiPath + `/sys-users-ps?size=${config.PAGE_SIZE}&page=${page}&query=${query}`, {responseType: 'json'})
    .then(resp => {
      return {
        dataCount: parseInt(resp.headers['x-total-count'], 10),
        data: resp.data
      }
    })
}

export function searchFilter (page, query, pageSize = config.PAGE_SIZE) {
  return axios.get(config.SERVER_URL + window.apiPath + `/sys-users-filter?page=${page}&size=${pageSize}${query ? '&' : ''}${query}`, {responseType: 'json'})
    .then(resp => resp)
}

export function findOneById (id) {
  return axios.get(config.SERVER_URL + window.apiPath + `/sys-users/${id}`, {responseType: 'json'})
    .then(resp => resp.data[0])
}

export function findAll () {
  return axios.get(config.SERVER_URL + window.apiPath + `/sys-users`, {responseType: 'json'})
    .then(resp => resp)
}

export function create (entity) {
  return axios.post(config.SERVER_URL + window.apiPath + '/sys-users', {...entity, responseType: 'json'})
}

export function update (entity) {
  return axios.put(config.SERVER_URL + window.apiPath + '/sys-users', {...entity, responseType: 'json'})
}

export function del (id) {
  return axios.delete(config.SERVER_URL + window.apiPath + '/sys-users/' + id, {responseType: 'json'})
}

export function resetPassword (id) {
  return axios.post(config.SERVER_URL + window.apiPath + '/sys-users-reset-pwd/' + id, {responseType: 'json'})
}

export function getCaptcha (phone, userName) {
  return axios.get(config.SERVER_URL + window.apiPath + `/sys-users-captcha?phone=${phone}&userName=${userName}`)
}

export function forgotPassword (form) {
  let entity = {responseType: 'json'}
  entity.userName = form.user
  entity.phone = form.phone
  entity.captcha = form.vercode
  entity.password = form.newpwd

  return axios.post(config.SERVER_URL + window.apiPath + '/sys-users-reset-password', entity)
}
